import router from '@system.router'
import routerConfig from '../json/routerConfig.json'
import Custom_page from "../plugins/pages.js"
import REPORT_SDK from "../sdks/report_sdk.js"
import TACTICS_SDK from "../sdks/tactics_sdk.js"
import AD_SDK from "../sdks/ad_sdk.js"
import AD_SDK_UTILS from "./ad_sdk_utils.js"
import COMMON_REPORT_UTILS from "./common_report_utils.js"
import TACTICS_SDK_UTILS from "./tactics_sdk_utils.js"
import LOG from "./log_utils.js"
import TOOLS_UTILS from "./tools_utils.js"
import DEVICE_UTILS from "./device_utils.js"
import AD_UTILS from "./ad_utils.js"
import POP_TOOLS from "./pop_utils.js"
/* @desc: 注入方法至全局 global,以便页面调用 */
const hook2global = global.__proto__ || global
const $utils = require('../helper/utils').default
const $apis = require('../helper/apis').default
hook2global.$utils = $utils
hook2global.$apis = $apis
hook2global.REPORT_SDK = REPORT_SDK
hook2global.TACTICS_SDK = TACTICS_SDK
hook2global.AD_SDK = AD_SDK
hook2global.TOOLS_UTILS = TOOLS_UTILS
hook2global.DEVICE_UTILS = DEVICE_UTILS
hook2global.AD_UTILS = AD_UTILS
hook2global.POP_TOOLS = POP_TOOLS
hook2global.LOG = LOG
hook2global.AD_SDK_UTILS = AD_SDK_UTILS
hook2global.COMMON_REPORT_UTILS = COMMON_REPORT_UTILS
hook2global.TACTICS_SDK_UTILS = TACTICS_SDK_UTILS
hook2global.Custom_page = Custom_page
try {
    hook2global.nearmeBrowser = require('@nearme.browser')
    hook2global.nearmePackage = require('@nearme.package')
} catch (error) { }
let global_data = {
    _THIS: null, // 当前页面上下文对象
    _APP: null, // app对象
    screenHeight: 0,//屏幕高度
    hotLineClick: false
}
/**
 * 更新公共属性
 */
const updateCommonData = async (pageInfo) => {
    global_data._THIS = pageInfo
    global_data._APP = pageInfo.$app.$def
    //更新页面来源
    let curObj = getPagesCodeInfo(
        Number(pageInfo.selectIndex) != NaN ? Number(pageInfo.selectIndex) : 0
    )
    pageInfo.pathUrl = curObj.pathUrl
    pageInfo.pageDetail.pathUrl = pageInfo.pathUrl
    pageInfo.pageDetail.pageOrigin = curObj.pageOrigin
    POP_TOOLS.changeCurrentView(global_data._THIS) //更新弹窗工具上下文
    if (global_data._APP.brand && global_data._APP.android && global_data._APP.oaid) {
        console.log(global_data._APP.brand, global_data._APP.android, global_data._APP.oaid, 'decvice-----')
        return
    }
    await initDeviceInfo(global_data._APP)
}
// 获取当前页面以及来源页面信息
const getPagesCodeInfo = (tabId = 0) => {
    // copy页面信息
    let originInfo = Object.assign({}, global_data._APP.pageCodeInfo)
    // 获取当前页面信息
    var page = router.getState()
    let pageInfo = routerConfig[`${page.path}`]
    // 当前来源页等于当前页 则不修改 this.pageCodeInfo
    if (pageInfo && originInfo.pageCode == pageInfo.pageCode && originInfo.pathCurUrl == pageInfo.pathUrl) {
        return global_data._APP.pageCodeInfo;
    }
    AD_SDK_UTILS.updataAdConfigData({ uploadFristPopClick: 3 })
    // 当前来源页等于当前页 则不修改 this.pageCodeInfo
    if (pageInfo && pageInfo.pageCode == routerConfig['/pagesA/Main'].pageCode0 && originInfo.pageCode == pageInfo[`pageCode${tabId}`] && originInfo.pathCurUrl == pageInfo[`pathUrl${tabId}`]) {
        return global_data._APP.pageCodeInfo;
    }

    global_data._APP.pageCodeInfo.pageOrigin = originInfo.pageCode
    global_data._APP.pageCodeInfo.pathUrl = originInfo.pathCurUrl


    if (pageInfo) {
        if (pageInfo.pageCode == routerConfig['/pagesA/Main'].pageCode0) {
            // 单独处理首页
            global_data._APP.pageCodeInfo.pageCode = pageInfo[`pageCode${tabId}`]
            global_data._APP.pageCodeInfo.pathCurUrl = pageInfo[`pathUrl${tabId}`]
        } else {
            global_data._APP.pageCodeInfo.pageCode = pageInfo.pageCode
            global_data._APP.pageCodeInfo.pathCurUrl = pageInfo.pathUrl
        }
    } else {
        global_data._APP.pageCodeInfo.pageCode = ""
        global_data._APP.pageCodeInfo.pathCurUr = ""
    }
    return global_data._APP.pageCodeInfo
}
const initDeviceInfo = async (_app) => {
    return new Promise(async (resolve) => {
        await DEVICE_UTILS.getInfo().then(res => {
            LOG('deviceInfo===>', res)
            let tempBrand = res.brand.toLowerCase()
            if (tempBrand == 'oppo' || tempBrand == 'realme' || tempBrand == 'oneplus') {
                tempBrand = 'oppo'
            } else {
                tempBrand = 'other'
            }
            global_data.screenHeight = Math.ceil(750 * res.screenHeight / res.screenWidth)
            _app.deviceInfo = res
            _app.brand = tempBrand
            _app.model = tempBrand + " " + res.model
        })
        /**
         * 获取androidId
         */
        await DEVICE_UTILS.getUserId().then(res => {
            _app.android = res.userId
            console.log(_app.android, 'decvice-----android')
        })
        /**
         * 获取OAID  
         */
        await DEVICE_UTILS.getOAID().then(res => {
            console.log(res.oaid, 'decvice-----oaid')
            _app.oaid = res.oaid
        })
        resolve()
    })
}
const login = () => {
    return new Promise((resolve, reject) => {
        $utils.getStorage('expirationTime').then(async res => {
            let now = new Date().getTime();
            if (now >= res) {
                $apis.example
                    .login({
                        android_id: global_data._APP.android,
                        oaid: global_data._APP.oaid,
                        brand: global_data._APP.brand,
                    })
                    .then((res) => {
                        if (res.status == 200) {
                            //存储过期时间为一天后
                            let now = new Date().getTime();
                            let expirationTime = now + 24 * 60 * 60 * 1000;
                            $utils.setStorage('expirationTime', expirationTime)
                            $utils.setStorage('token', res.data.token)
                            $utils.setStorage('userInfo', res.data)
                        }
                        resolve(res.data)
                    })
                    .catch((error) => { reject(error) })
            } else {
                resolve()
            }
        })
    })
}
/**
 * 当前页面路由跳转当前页 只处理路由附带的参数
 * @param param 路由参数
 */
const routerJumpSelfHandeler = (param) => {
    for (let key in param) {
        if (key == 'selectIndex') {
            global_data._THIS[key] = Number(param[key])
        } else {
            global_data._THIS[key] = param[key]
        }
    }
}
const global_utils = {
    global_data,
    initDeviceInfo,
    login,
    updateCommonData,
    routerJumpSelfHandeler
}
hook2global.GLOBAL_UTILS = global_utils
export default global_utils